<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <el-row>
        <el-col :span="15">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>

      <el-form :model="queryParams" ref="queryRef" label-width="120" @submit.native.prevent>
        <el-row>
          <el-col :span="15">
            <el-form-item label="实验室房间名称：" prop="roomName">
              <el-input clearable maxlength="100" v-model="queryParams.roomName" placeholder="请输入实验室房间名称"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-row justify="end">
              <el-button type="success" @click.enter="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">房间列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button link type="success" icon="Plus" @click="addClick">新增</el-button>
          </el-row>
        </el-row>
        <el-table ref="mainTableRef" class="business" v-loading="loading" :data="roomTable"
          :row-class-name="tableRowClass" @row-click="rowClick" @selection-change="handleSelectionChange">
          <el-table-column label="房间名称" align="center" prop="roomName" />
          <el-table-column label="房间号" align="center" prop="roomNumber" />
          <el-table-column label="上次记录时间" align="center" prop="recordTime" />
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 搜索条件区域 -->
      <el-form :model="roomDataForm" ref="roomDataRef" label-width="125" :rules="rules">
        <el-row>
          <el-col :span="6">
            <el-form-item label="房间号：" prop="roomNumber" label-width="70">
              <el-input clearable maxlength="100" v-model="roomDataForm.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="房间名称：" prop="roomName" label-width="80">
              <el-input clearable maxlength="100" v-model="roomDataForm.roomName" placeholder="请输入房间名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="温度范围（°C）：" prop="temperature">
              <el-input clearable maxlength="100" v-model="roomDataForm.temperature" placeholder="请输入温度范围（°C）" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="湿度范围（%h）：" prop="humidity">
              <el-input clearable maxlength="100" v-model="roomDataForm.humidity" placeholder="请输入湿度范围（%h）" />
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-row justify="end">
              <el-button size="small" style="margin-top: 4px" type="success" @click="addRoom(false)">保存</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="2">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form label-width="80px" :model="roomForm" ref="roomRef" :disabled="!roomDataForm.roomId">
        <el-row>
          <el-col :span="6">
            <el-form-item label="记录人：" prop="createUserId" label-width="70">
              <el-select v-model="roomForm.createUserId" placeholder="请选择记录人" clearable>
                <el-option v-for="item in proxy.addListNoLimit(
                  userList,
                  'userId',
                  'nickName'
                )" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期：">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row justify="end">
              <el-button type="success" @click="getcheckListLedger">搜索</el-button>
              <el-button class="resetBtn" @click="resetBtn">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <!-- /搜索条件区域 -->

      <!-- 技术指标表格 -->
      <el-row style="justify-content: space-between">
        <el-row>
          <p class="pinformation">温湿度记录列表</p>
          <p class="totalStyle">共 {{ roomTotal }} 条数据</p>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button link icon="Plus" @click="addOtin">新增</el-button>
          </el-row>
        </el-row>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button link icon="EditPen">记录人批量签字</el-button>
          <el-button link icon="DocumentDelete">导出温湿度记录</el-button>
        </el-row>
      </el-row>

      <el-table ref="sub1TableRef" class="business" v-loading="targetTableLoading" :data="targetList"
        @selection-change="outSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="测定时间" align="center" prop="recordDate" />
        <el-table-column label="当前温度" align="center" prop="currentTem" />
        <el-table-column label="当前湿度" align="center" prop="currentHum" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="记录人" align="center" prop="createUserId">
          <template #default="scope">
            {{
              proxy.getItemByArray(
                userList,
                "userId",
                scope.row.createUserId,
                "nickName"
              )
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="success" @click="roomRecordEdit(scope.row)">编辑</el-button>
            <el-button link type="success" @click="roomRecordDel(scope.row)">删除</el-button>
            <el-button link type="success">签字</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- /技术指标表格 -->
      <pagination v-show="roomTotal > 0" :total="roomTotal" v-model:page="roomForm.pageNum"
        v-model:limit="roomForm.pageSize" @pagination="getcheckListLedger" />
      <!-- @pagination="" -->
    </el-card>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="roomOpen" :title="otinTitle" @close="dialogClose">
      <!-- @close="closedInDialog" -->
      <el-form label-width="110" ref="otinRef" :model="form" :rules="otinRules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="测定时间：" prop="recordDate">
              <el-date-picker v-model="form.recordDate" type="datetime" placeholder="请选择测定时间"
                value-format="YYYY-MM-DD HH:mm" format="YYYY-MM-DD HH:mm" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前温度：" prop="currentTem">
              <el-input v-model="form.currentTem" maxlength="100" clearable placeholder="请输入当前温度" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前湿度：" prop="currentHum">
              <el-input v-model="form.currentHum" maxlength="100" clearable placeholder="请输入当前湿度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="备注：" prop="remark">
              <el-input clearable placeholder="请输入备注" maxlength="100" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录人：" prop="createUserId">
              <el-select v-model="form.createUserId" placeholder="请选择记录人" clearable>
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="save">保 存</el-button>
          <el-button type="danger" @click="roomOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Instrument">
import { listUser } from "@/api/contract/check";
import { getCurrentTimeDetails, getCurrentUser } from "@/api/common";
import {
  listRoomList,
  formRoom,
  checkListLedger,
  addRoomTable,
  roomSave,
  recordEdit,
  delRoomRecord,
} from "@/api/resource/room";

const { proxy } = getCurrentInstance();

const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const roomTable = ref([]);
const targetTableLoading = ref(false);
const dateRange = ref([]);
const roomOpen = ref(false);
const otinTitle = ref("新增温湿度记录");
const roomForm = ref({
  pageNum: 1,
  pageSize: 10,
  createUserId: -1,
});
onMounted(() => {
  nextTick(() => {
    getList();
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 73 },
        { tableName: "sub1", bottomHeight: 73 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub1", bottomHeight: 73 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub1", bottomHeight: 21 },
]);

const roomDataForm = ref({});

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    roomNumber: [
      { required: true, message: "房间号不能为空", trigger: "blur" },
    ],
    roomName: [
      { required: true, message: "房间名称不能为空", trigger: "blur" },
    ],
  },
  otinRules: {
    recordDate: [
      { required: true, message: "测定时间不能为空", trigger: "blur" },
    ],
    currentHum: [
      { required: true, message: "湿度不能为空", trigger: "blur" },
    ],
    currentTem: [
      { required: true, message: "温度不能为空", trigger: "blur" },
    ],
    createUserId: [
      { required: true, message: "记录人不能为空", trigger: "blur" },
    ],
  },

});

const { queryParams, form, rules, otinRules } = toRefs(data);

/** 查询仪器档案列表 */
function getList() {
  loading.value = true;
  listRoomList(queryParams.value).then((response) => {
    roomTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
// function reset() {
//   form.value = {};
//   proxy.resetForm("");
// }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.instrumentId);
}

const roomIds = ref([]);
function outSelectionChange(selection) {
  roomIds.value = selection.map((item) => item.outinId);
}

const roomTotal = ref(0);

const targetList = ref([]);

function resetBtn() {
  proxy.resetForm("roomRef");
  dateRange.value = [];
  getcheckListLedger();
}

function rowClick(row) {
  proxy.resetForm("roomRef");
  dateRange.value = [];
  if (proxy.$refs["roomDataRef"]) {
    proxy.$refs["roomDataRef"].clearValidate();
  }
  formRoom(row.roomId).then((res) => {
    roomDataForm.value = res.data;
    heightBright.value = row.roomId;
    getcheckListLedger();
  });
}

function getcheckListLedger() {
  roomForm.value = {
    params: {
      beginTime: dateRange.value[0],
      endTime: dateRange.value[1],
    },
    roomId: roomDataForm.value.roomId,
    pageNum: roomForm.value.pageNum,
    pageSize: roomForm.value.pageSize,
    createUserId: roomForm.value.createUserId,
  };
  checkListLedger(roomForm.value).then((res) => {
    targetList.value = res.rows;
    roomTotal.value = res.total;
  });
}

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.roomId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

function addOtin() {
  addRoom(true).then((res) => {
    otinTitle.value = "新增温湿度记录";
    roomOpen.value = true;
    getCurrentTimeDetails().then((res) => {
      form.value.recordDate = res.data;
    });
    getCurrentUser().then((res) => {
      form.value.createUserId = res.data;
    });
  });
}

function save() {
  proxy.$refs["otinRef"].validate((valid) => {
    if (valid) {
      form.value.roomId = roomDataForm.value.roomId;
      addRoomTable(form.value).then((res) => {
        roomOpen.value = false;
        proxy.$modal.msgSuccess("保存成功");
        getcheckListLedger();
        getList()
      });
    }
  })
}

function useCountChange() {
  nextTick(() => {
    if (form.value.useCount > form.value.remainCount) {
      proxy.$modal.msgError(
        "本次使用量不可以超过剩余量,已更改为可以使用的最大量"
      );
      form.value.remainCount1 = 0;
      form.value.useCount = form.value.remainCount;
    } else {
      form.value.remainCount1 = form.value.remainCount - form.value.useCount;
    }
  });
}

function addRoom(isAuto) {
  // roomDataRef
  return new Promise((resolve, reject) => {
    proxy.$refs["roomDataRef"].validate((valid) => {
      if (valid) {
        roomSave(roomDataForm.value).then((res) => {
          if (!isAuto) {
            proxy.$modal.msgSuccess("保存成功");
          }
          roomDataForm.value.roomId = res.data;
          getList();
          resolve();
        });
      }
    });
  });
}

function roomRecordEdit(row) {
  recordEdit(row.recordId).then((res) => {
    form.value = res.data;
    roomOpen.value = true;
    otinTitle.value = "编辑温湿度记录";
  });
}

function dialogClose() {
  form.value = {};
  if (proxy.$refs["otinRef"]) {
    proxy.$refs["otinRef"].clearValidate();
  }
}

function roomRecordDel(row) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delRoomRecord(row.recordId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getcheckListLedger();
        getList()
      });
    })
    .catch(() => { });
}

function addClick() {
  roomDataForm.value = {};
  roomForm.value = {};
  dateRange.value = [];
  targetList.value = [];
  roomTotal.value = 0;
  if (proxy.$refs["roomDataRef"]) {
    proxy.$refs["roomDataRef"].clearValidate();
  }
}
</script>

<style lang="scss" scoped></style>
